//
//  ViewController.m
//  stone-story
//
//  Created by liu dodo on 12-9-23.
//  Copyright (c) 2012年 liu dodo. All rights reserved.
// nx9xJ9mR7rb4

#import "ViewController.h"


@interface ViewController ()

@end

@implementation ViewController
@synthesize queue;
@synthesize resultArray=_resultArray;
@synthesize delegate;
- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    [self.view setBackgroundColor:[UIColor redColor]];
    [self LoadXmlTest];
    
   
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
     return (interfaceOrientation == UIInterfaceOrientationLandscapeLeft ||interfaceOrientation==UIInterfaceOrientationLandscapeRight  );
}
- (void)viewWillAppear:(BOOL)animated {
    
    CGSize size = CGSizeMake(250,100); // size of view in popover
    self.contentSizeForViewInPopover = size;
    
    [super viewWillAppear:animated];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [db close];
}

//测试加载XML
-(void)LoadXmlTest
{
    _resultArray = [[NSMutableArray alloc] init];

    HUD = [[MBProgressHUD alloc] initWithView:self.view];

    [self.view addSubview:HUD];
    HUD.delegate = self;
    // HUD.labelText = @"Loading...";
    HUD.mode=MBProgressHUDModeIndeterminate;
    [HUD show:YES];

    //传健请求队列
    if (![self queue]) {
    
        [self setQueue:[[NSOperationQueue alloc] init]];
    }
    NSURL *url = [NSURL URLWithString:ProductCategroyAPI];
   
    ASIHTTPRequest *request2 = [ASIHTTPRequest requestWithURL:url];
    [request2 setDelegate:self.delegate];
    [request2 setDidFinishSelector:@selector(requestDone:)];
    [request2 setDidFailSelector:@selector(requestWentWrong:)];
    [[self queue] addOperation:request2];
    
}



//when the request is done
//如果请求成功的时候调用的函数
-(void)requestDone:(ASIHTTPRequest *)request
{
    
    //NSLog(@"%@",[request responseString]);
    NSData *XMLData =[request responseData];
    
    //生成CXMLDocument对象：
    CXMLDocument *document = [[CXMLDocument alloc] initWithData:XMLData options:0 error:nil];
    //使用parseDire来解析(推荐):
    [self parseDire:document];
    [HUD hide:YES afterDelay:0];
   
}
//when the rquest ment error
//当请求遇见错误的时候调用的函数
- (void)requestWentWrong:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    NSError *error = [request error];
    NSLog(@"%@",error);
    
  	MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
	
	// Configure for text only and offset down
	hud.mode = MBProgressHUDModeText;
	hud.labelText = NSLocalizedString(@"连接超时,请检查网络...",@"");
	hud.margin = 10.f;
	hud.yOffset = 120.f;
	hud.removeFromSuperViewOnHide = YES;
	[hud hide:YES afterDelay:3];
  
    
}

#pragma mark --解析函数
- (void)parseDire:(CXMLDocument *) document
{
     NSLog(@"dodo 开始使用parseDire解析." );
    NSArray *items = NULL;
    //注意，这是用XML PATH来取得元素集:
    items = [document nodesForXPath:@"//Category" error:nil];
    //NSLog(@"dodo parseDire解析- 元素数: %d", items.count) ;
    for (CXMLElement *element in items)
    {
        if ([element isKindOfClass:[CXMLElement class]])
        {
            NSMutableDictionary *item = [[NSMutableDictionary alloc] init];
            for (int i = 0; i < [element childCount]; i++)
            {
                if ([[[element children] objectAtIndex:i]
                     isKindOfClass:[CXMLElement class]])
                {
                    [item setObject:[[element childAtIndex:i] stringValue]
                             forKey:[[element childAtIndex:i] name]
                     ];
                }
            }
            [_resultArray addObject:item];
            
        }
    }
    
    
     NSLog(@"数组中元素数: %d", _resultArray.count );
     //然后从控制台读取相关内容:
    
    
    [self FMDB_init];
    [self createTable];
    [self deleteRecord];
    
     for (NSMutableDictionary* dict in _resultArray) {
     // NSLog(@"子字典元素数: %d", dict.count);
     /* NSLog(@"类别ID是什么: %@", [dict objectForKey:@"CategoryID"] );
     NSLog(@"类别名称是: %@\n", [dict objectForKey:@"CategoryName"] );
      NSLog(@"类别的父类别是: %@\n", [dict objectForKey:@"ParentCategoryID"] );
           NSLog(@"备注是: %@\n", [dict objectForKey:@"Note"] );*/
         
         if([self isExistTable:@"tb_categroy" InTheDateBase:db]){
             [db executeUpdate:@"INSERT INTO tb_categroy (categroy_id,categroy_name,parentcategory_id,note) VALUES (?,?,?,?)",[dict objectForKey:@"CategoryID"],[dict objectForKey:@"CategoryName"],[dict objectForKey:@"ParentCategoryID"],[dict objectForKey:@"Note"]];
            
         }
         else {
             NSLog(@"table db.Products have not exist!");
         }
     
     }
    
    [self queryTable];
     
}


#pragma mark - 数据库操作
//创建或打开数据库
- (void)FMDB_init//1
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"db_stoneStory.db"];
    
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    db= [FMDatabase databaseWithPath:dbPath];
    if (![db open]) {
        NSLog(@"Could not open db.");
        return ;
    }
    else {
        NSLog(@"open db. success!");
    }
    
    
    
}
//创建表
- (void)createTable
{
    //创建一个名为User的表，四个字段 书的ID,书的图片文件名,书的pdf文件名,书的排号
    if(![self isExistTable:@"tb_categroy" InTheDateBase:db])
        [db executeUpdate:@"CREATE TABLE tb_categroy (categroy_id text,categroy_name text,parentcategory_id text,note text)"];
    else {
        NSLog(@"table tb_categroy have exist!");
    }
}

//插入数据
- (void)insertRecord
{
    if([self isExistTable:@"tb_categroy" InTheDateBase:db])
    {
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:1],@"aaa.jpg"];
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:2],@"bbb.jpg"];
        //[db executeUpdate:@"INSERT INTO Products (product_id,product_image) VALUES (?,?)",[NSNumber numberWithInt:3],@"ccc.jpg"];
    }
    else
    {
        NSLog(@"table tb_categroy have not exist!");
    }
}

//查询
- (void)queryTable
{
    //返回数据库中第一条满足条件的结果
    //   NSString *aa=[db stringForQuery:@"SELECT Name FROM User WHERE Age = ?",@"20"];
    
    //返回全部查询结果
    FMResultSet *rs=[db executeQuery:@"SELECT * FROM tb_categroy ORDER BY categroy_id ASC"];
    
    //rs=[db executeQuery:@"SELECT * FROM User WHERE Age = ?",@"20"];
    
    while ([rs next])
    {
        NSLog(@"\n categroy_id:%@ \n categro_image:%@ \n  parentcategory_id:%@ \n note:%@ \n ",[rs stringForColumn:@"categroy_id"],[rs stringForColumn:@"categroy_name"],[rs stringForColumn:@"parentcategory_id"],[rs stringForColumn:@"note"]);
    }
    [rs close];
    [db close];
}


//更新数据 将“张三”更改为“李四”
-(void)updateRecord
{
    
    [db executeUpdate:@"UPDATE User SET Name = ? WHERE Name = ? ",@"李四",@"张三"];
    
}


//删除数据
- (void)deleteRecord
{
    if([self isExistTable:@"tb_categroy" InTheDateBase:db])
    {
        [db executeUpdate:@"DELETE FROM tb_categroy "];
    }
    else
    {
        NSLog(@"table tb_categroy have not exist!");
    }
}


//判断是否存在该表
-(BOOL)isExistTable:(NSString*)tablename InTheDateBase:(FMDatabase *)tdb {
    
    FMResultSet *rs = [tdb executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tablename];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
        NSLog(@"isTableOK %d", count);
        
        if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    
    return NO;
}






@end
